package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private  StringRedisTemplate stringRedisTemplate;

    @Autowired
    private FollowServiceImpl followService;

    @Override
    public Result querryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户  查询到的直接设置相关信息
        records.forEach(blog -> {
            this.setBlog(blog);
            this.setLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {
        //获取当前用户的id
        Long userId = UserHolder.getUser().getId();
        //去redis中查看该对象是否点过赞
        String key= BLOG_LIKED_KEY+id;
       // Boolean isLiked = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        //根据scoreSet中是否存在score来判断该用户是否点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if(score==null){
            //该用户没有点赞,可以点赞
            //首先跟新数据库
            boolean isOk = update().setSql("liked=liked+1").eq("id", id).update();
            if(isOk){
                //更新redis
                //stringRedisTemplate.opsForSet().add(key,userId.toString());
                //使用sortSet通过增加当前时间戳来进行顺序判断
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }
        else
        {
            //该用户已经点赞过了
            //先去数据库更新
            boolean isOk2 = update().setSql("liked=liked-1").eq("id", id).update();
            if(isOk2){
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }

        return Result.ok();
    }

    @Override
    public Result querryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY+id;
        //查询点赞前五的用户
        Set<String> range = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(range==null||range.isEmpty())
        {
            //没有点赞的用户,返回空集合
            return Result.ok(Collections.EMPTY_LIST);
        }
        //拆解用户id
        List<Long> ids= range.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr=StrUtil.join(",",ids);
        //根据用户id查询用户,将user处理为UserDTO对象 where id in (5,1) order by field (id ,5,1)
        List<UserDTO> userDTOS = userService.query().in("id", ids).last("order by field(id," + idStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        /*// 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean save = save(blog);
        if(!save)
        {
            return Result.fail("发布博客失败,请稍后重试");
        }
        //查询作者的粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        //遍历这些用户,并且将博客的id写入到用户对应的redis信箱之中
        for (Follow follow : follows) {
             Long userId = follow.getUserId();
            String key="feed:"+userId;
            stringRedisTemplate.opsForZSet().add("key",blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());*/
        //获取当前用户的id
        Long userId = UserHolder.getUser().getId();
        blog.setUserId(userId);
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("发布博客失败,请重试");
        }
        //报错到数据库成功,获取粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", userId).list();
        for (Follow follow : follows) {
            String key="feed:"+follow.getUserId();
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }

        return Result.ok(blog.getId());


    }

    @Override
    public Result querryBlogOfFollow(Long max, Integer offset) {
        //获取当前用户的id
        Long userId = UserHolder.getUser().getId();
        //获取redis中的值
        String key = "feed:" + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);

        //判断非空
        if (typedTuples == null || typedTuples.isEmpty())
        {
            return Result.ok();
        }
        //解析blogid(key) 时间戳(score) offset
        List<Object> ids=new ArrayList<>(typedTuples.size());
        long mintime=0; //这里的最短时间就是下一次查询的最大时间
        int os=1; //用来处理步长
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            ids.add(Long.valueOf(typedTuple.getValue()));
            //获取最后一次的时间戳,以及需要跨过的长度
            long time = typedTuple.getScore().longValue();
            if(mintime==time){
                os++;
            }else
            {
                mintime=time;
                os=1;
            }
        }

        //查数据库,使用上边的ids
        String idstr=StrUtil.join(",",ids);
        List<Blog> blogs = query().in("id", ids).last("order by field(id," + idstr + ")").list();
        for (Blog blog : blogs) {
            this.setBlog(blog);
            this.setLiked(blog);
        }
        ScrollResult r =new ScrollResult();
        r.setList(blogs);
        r.setOffset(os);
        r.setMinTime(mintime);

        return Result.ok(r);
    }

    @Override
    public Result querryBlogById(Long id) {
        //根据传进来的id查询博客
        Blog blog = getById(id);
        //判断是否存在
        if(blog==null)
        {
            return Result.fail("查询的博客不存在");
        }
        //封装用户头像和名字
        setBlog(blog);
        //判断是否点赞过
        setLiked(blog);
        return Result.ok(blog);


    }

    //构建blog
    public void setBlog(Blog blog)
    {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
    }

    //判断有没有点赞信息
    public void setLiked(Blog blog)
    {
       /* //获取用户id
        Long userId= UserHolder.getUser().getId();
        //blog的key
        String key=RedisConstants.BLOG_LIKED_KEY+blog.getId();
        //获取点赞信息
        Boolean isLiked = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
            //点赞过了,设置高亮
        blog.setIsLike(BooleanUtil.isTrue(isLiked));
*/
        //使用sortSet来判断
     //获取登录用户
        UserDTO user = UserHolder.getUser();
        if(user==null)
        {
            //用户未登录,不用执行操作
            return;
        }
        Long userId = user.getId();
        String key= BLOG_LIKED_KEY+blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score!=null? true:false);
    }

}
